package com.yhgarden.bbs.model.interceptor;

import com.yhgarden.bbs.model.constants.YhbbsConstants;
import com.yhgarden.bbs.model.enums.StatusCode;
import com.yhgarden.bbs.model.exception.YhbbsException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session =  request.getSession();
        if(session == null){
            throw new YhbbsException(StatusCode.USER_NOT_LOGIN,this.getClass());
        }
        String uri = request.getRequestURI();
        System.out.println("=============================uri=======================:"+uri);
        String urlType = request.getHeader(YhbbsConstants.REQUEST_HEADER_URL_TYPE);
        System.out.println("==========================urlType==========================================:"+urlType);
        if(urlType == null){
            throw new YhbbsException(StatusCode.ILLEGAL_ACCESS_INTERFACE,this.getClass());
        }
        //判断是否为PC端
        if(YhbbsConstants.REQUEST_HEADER_URL_TYPE_PC.equals(urlType)){
            //判断用户是否登录，如果未登录，则抛错
            if(session.getAttribute(YhbbsConstants.USER_SESSION_KEY) == null){
                throw new YhbbsException(StatusCode.USER_NOT_LOGIN,this.getClass());
            }
        }
        //如果是后台
        else if(YhbbsConstants.REQUEST_HEADER_URL_TYPE_ADMIN.equals(urlType)){
            //判断用户是否登录，如果未登录，则抛错
            if(session.getAttribute(YhbbsConstants.SYSTEM_USER_SESSION_KEY) == null){
                throw new YhbbsException(StatusCode.USER_NOT_LOGIN,this.getClass());
            }
        }else {
            throw new YhbbsException(StatusCode.ILLEGAL_ACCESS_INTERFACE,this.getClass());
        }
        return true;
    }

}
